package com.android.fragmentdemo.definervlayoutmanager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

public class SlideLayoutManager extends RecyclerView.LayoutManager {

    private static final float DEFAULT_SCALE = 0.5f;

    private final int mMaxVisibleCount;
    private final RecyclerView mRecyclerView;
    private final ItemTouchHelper mItemTouchHelper;

    public SlideLayoutManager(int mMaxVisibleCount, RecyclerView mRecyclerView, ItemTouchHelper mItemTouchHelper) {
        this.mMaxVisibleCount = mMaxVisibleCount;
        this.mRecyclerView = mRecyclerView;
        this.mItemTouchHelper = mItemTouchHelper;
    }

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        removeAllViews();
        detachAndScrapAttachedViews(recycler);
        int layoutCount = Math.min(mMaxVisibleCount, getItemCount());
        for (int i = layoutCount - 1; i >= 0; i--) {
            View child = recycler.getViewForPosition(i);
            addView(child);
            measureChildWithMargins(child, 0, 0);
            int childWidth = getDecoratedMeasuredWidth(child);
            int childHeight = getDecoratedMeasuredHeight(child);
            int widthSpace = getWidth() - childWidth;
            int heightSpace = getHeight() - childHeight;
            layoutDecoratedWithMargins(child, widthSpace / 2, heightSpace / 2, widthSpace / 2 + childWidth, heightSpace / 2 + childHeight);
            float scaleValue = (float) Math.pow(DEFAULT_SCALE, i);
            child.setScaleX(scaleValue);
            child.setScaleY(scaleValue);

            if (i == 0) {
                child.setOnTouchListener((view, event) -> {
                    view.performClick();
                    RecyclerView.ViewHolder viewHolder = mRecyclerView.getChildViewHolder(child);
                    if (MotionEvent.ACTION_DOWN == event.getAction()) {
                        mItemTouchHelper.startSwipe(viewHolder);
                    }
                    return false;
                });
            } else {
                child.setOnTouchListener(null);
            }
        }
    }
}
